package helper.base

import java.io.File
import java.io.IOException

object FileHelper {
    object Expand {
        fun File.createIfNotExists() {
            if (this.exists()) return
            try {
                this.parentFile.mkdirs()
                this.createNewFile()
            } catch (e: IOException) {
                println("无法创建文件：${e.message}")
            }
        }

        fun String.toFile(): File {
            return File(this)
        }

        fun String.toCreatedFile(): File {
            val file = File(this)
            file.createIfNotExists()
            return file
        }

        fun String.createDirectories() {
            this.toFile().mkdirs()
        }

        fun String.createFileIfNotExists() {
            this.toFile().createIfNotExists()
        }
    }

    fun getNewMaxIndexDirFileString(
        dirString: String,
        fileString: String,
        maxAttempts: Int = 1000,
    ): String {
        var index = 0
        while (index < maxAttempts) {
            val returnFileString = "$dirString\\${fileString}${index}"
            val file = File(returnFileString)
            if (file.exists()) {
                index += 1
            } else {
                return returnFileString
            }
        }
        throw IOException("达到最大尝试次数：$maxAttempts")
    }

    fun printDirectoryContents(
        directory: File,
        maxDepth: Int,
        currentDepth: Int = 0,
    ) {
        if (directory.isDirectory) {
            directory.listFiles()?.let { files ->
                for (file in files) {
                    if (file.isDirectory && currentDepth < maxDepth) {
                        printDirectoryContents(
                            file,
                            maxDepth,
                            currentDepth + 1,
                        )  // 递归打印子目录
                    } else if (file.isFile) {
                        println("${"\t".repeat(currentDepth)}${file.name}")  // 打印文件名
                    }
                }
            } ?: run {
                println("目录 ${directory.path} 不能被读取或不存在")
            }
        }
    }
}